﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HynuIOTA.IRespository;

namespace HynuIOTA.Respository
{
    public partial class DBSession : IDBSession
    {

        /// <summary>
        /// 将实体更改保存到数据库
        /// </summary>
        /// <returns></returns>
        public int SaveChanges()
        {
            try
            {
                return EFFactory.GetDBContext().SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                throw ex;
            }
        }

        public Task<int> SaveChangesAsync()
        {
            try
            {
                return EFFactory.GetDBContext().SaveChangesAsync();
            }
            catch (DbEntityValidationException ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// Sql语句执行命令
        /// </summary>
        /// <param name="sqlCommand"></param>
        /// <returns></returns>
        public int ExecuteSqlCommand(string sqlCommand)
        {
            return EFFactory.GetDBContext().Database.ExecuteSqlCommand(sqlCommand);
        }

        /// <summary>
        /// Sql语句执行命令 - 异步
        /// </summary>
        /// <param name="sqlCommand"></param>
        /// <returns></returns>
        public Task<int> ExecuteSqlCommandAync(string sqlCommand)
        {
            return EFFactory.GetDBContext().Database.ExecuteSqlCommandAsync(sqlCommand);
        }

        /// <summary>
        /// Sql语句执行查询
        /// </summary>
        /// <param name="sqlQuery"></param>
        /// <returns></returns>
        public DbRawSqlQuery<T> SqlQuery<T>(string sqlQuery)
        {
            return EFFactory.GetDBContext().Database.SqlQuery<T>(sqlQuery);
        }
    }
}
